<?php

namespace App\Http\Controllers\Wechat;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Models\Shop\Cart;

class CartController extends Controller
{
    function __construct()
    {
        view()->share([
            '_cart' => 'on'
        ]);
    }

    public function index()
    {
//        $count = [];
//        $total_price = 0;
//        $num = 0;
        $carts = Cart::with('product')->where('customer_id', session('wechat.customer.id'))->get();
        $count = Cart::count_cart($carts);

//        foreach ($carts as $v) {
//            $total_price += $v->product->price * $v->num;
//            $num += $v->num;
//        }
//        $count['total_price'] = $total_price;
//        $count['num'] = $num;
//        return $carts;
        return view('wechat.carts.index', compact('carts', 'count'));
    }

    /***
     * 增加数量
     */
    public function add(Request $request)
    {
        $id = $request->id;
        Cart::where('id', $id)->increment('num');
        return Cart::count_cart();
    }

    /***
     * 减少
     */
    public function sub(Request $request)
    {
          Cart::where('id', $request->id)->decrement('num');
        return Cart::count_cart();
    }

    /***
     * 添加商品到购物车
     */
    public function add_cart(Request $request)
{
    $product_id = $request->product_id;
    $cart = Cart::where('product_id', $product_id)->where('customer_id', session('wechat.customer.id'))->first();

    //购物车是否有当前商品，有数量加1
    if (!$cart) {
        //创建新数据
        $data['product_id'] = $request->product_id;
        $data['customer_id'] = session('wechat.customer.id');
        Cart::create($data);
    }else{
        Cart::where('id', $cart->id)->increment('num');
    }
}

    /***
     * 删除商品
     */
    public function delete_cart(Request $request){
        $id = $request->id;
        Cart::destroy($id);
        return Cart::count_cart();
    }
}
